package com.hospital.servlet;

import com.hospital.dao.DepartmentDAO;
import com.hospital.model.Department;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/api/departments")
public class DepartmentServlet extends HttpServlet {
    private DepartmentDAO departmentDAO = new DepartmentDAO();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        
        List<Department> departments = departmentDAO.findAll();
        
        PrintWriter out = response.getWriter();
        out.print("[");
        for (int i = 0; i < departments.size(); i++) {
            Department dept = departments.get(i);
            out.print("{");
            out.print("\"id\":" + dept.getId() + ",");
            out.print("\"name\":\"" + dept.getName() + "\",");
            out.print("\"description\":\"" + (dept.getDescription() != null ? dept.getDescription() : "") + "\"");
            out.print("}");
            if (i < departments.size() - 1) {
                out.print(",");
            }
        }
        out.print("]");
    }
}